import styled from "@emotion/styled";
import { ReactNode, useEffect, useState } from "react";
import Markdown from "react-markdown";
import { windowSize } from "util/window";
import { boxBg } from "components/style";
import { contentObj } from "../edit/edit.slice";
import gfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { tomorrow } from "react-syntax-highlighter/dist/esm/styles/prism";
import { useNavigate, useParams } from "react-router";
import { Breadcrumb } from "antd";
import { Icon } from "components/lib";
import { GetContent } from "http/content-http";
import { useDispatch } from "react-redux";
import { mainActions } from "./main.slice";
import { useAsync } from "util/use-async";
import LoadingTip from "components/loadingTip";

const ContentScreen = () => {
  const dispatch = useDispatch();
  const { id } = useParams();

  const [content, setContent] = useState(undefined as contentObj | undefined);

  useEffect(() => {
    GetContent({ id, isOpen: true }).then((res: contentObj[]) => {
      setContent(res[0]);
    });
  }, [id]);
  const { run, isLoading } = useAsync();

  useEffect(() => {
    if (content && content.fileUrl) {
      run(
        fetch(content.fileUrl)
          .then(async (res) => {
            setMd(await res.text());
          })
          .catch((error) => {
            setMd(error);
          })
      );
    }
  }, [content, run]);

  const navigate = useNavigate();
  const onToHome = () => {
    dispatch(mainActions.onSetTag(""));
    navigate("/content");
  };

  const [md, setMd] = useState("");

  // 代码高亮
  const renderers = {
    code: ({ language, value }: { language: string; value: ReactNode }) => {
      return (
        <SyntaxHighlighter
          style={tomorrow}
          language={language}
          children={value}
        />
      );
    },
  };
  return (
    <Container>
      <NavBox>
        <Breadcrumb>
          <Breadcrumb.Item onClick={onToHome}>
            <Icon name={"icon-shouyefill"}></Icon>
          </Breadcrumb.Item>
          <Breadcrumb.Item>{content?.title}</Breadcrumb.Item>
        </Breadcrumb>
      </NavBox>
      <Box>
        {isLoading ? (
          <LoadingTip spinning={isLoading} />
        ) : (
          <Markdown plugins={[gfm]} children={md} renderers={renderers} />
        )}
      </Box>
    </Container>
  );
};

export default ContentScreen;

const NavBox = styled.div`
  background-color: ${boxBg};
  width: 100%;
  padding: 1rem 2rem;
  margin-bottom: 2rem;
`;

const Box = styled.div`
  background-color: ${boxBg};
  padding: 2rem;
  width: 100%;
  img {
    max-width: 100%;
  }
`;

const Container = styled.div`
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
  height: 100%;
  min-width: 36rem;
  min-height: calc(100vh - 4rem);
  padding: 2rem;
  @media screen and (min-width: ${windowSize.medium}px) {
    width: calc(100% - 24rem);
  }
`;
